---
--类名: CaptainMyCollectsView.lua
--创建日期: 2018-9-22
--创建人: 宋建邦
--功能描述: 我的收藏view
--修改内容:
local AvatarFactory = app:getClass("AvatarFactory")
local BaseIcon = Res.BaseIcon
local GRes = Res
local Res = {
     CollectView = "ui2/room/Scene_room_collect.csb",
     TypeNode = "ui2/room/Node_collect_tlt.csb",
}

local CaptainMyCollectsView = class("CaptainMyCollectsView", app.mvc.ViewBase)
CaptainMyCollectsView.VIEW_ROOT_RES = Res.CollectView

function CaptainMyCollectsView:ctor(m)
    self.model = m
    self.super.ctor(self)
end

function CaptainMyCollectsView:init()
    self:setBackGroundColorType(0)
    self:setNodeEventEnabled(true)  
    
    self.itemNode = cc.CSLoader:createNode(BaseIcon)
    self.itemNode:retain()

    local listView = ccui.ListView:create()
    -- listView:setBackGroundColor(display.COLOR_RED)
    -- listView:setBackGroundColorOpacity(70)
    -- listView:setBackGroundColorType(1)    

    local sv = self._root:findChild("Panel/Panel_bag/ScrollView")
    listView:setContentSize(sv:getContentSize())
    listView:setAnchorPoint(sv:getAnchorPoint())
    listView:setPosition(cc.p(sv:getPositionX(), sv:getPositionY()))
    listView:setBounceEnabled(true)
    sv:getParent():addChild(listView)
    sv:hide()

    self.collectList = listView
    self:initGroups()
    self:refreshRedPoint()

    self._root:findChild("Panel/Button_close"):addClickEventListener(function(sender)
        app:sendMsg("CaptainController", "closeCollectView")
    end)   

    self.redpointHandler =EM:on(app:getInst("CaptainModelRedPoint").RedPointChange, function()
        -- dump(self)
        self:refreshRedPoint()
    end)
end

function CaptainMyCollectsView:initGroups()
    self.gbtns = {}
    self.funcs = {}
    self.gnames = {}
    local lastBtn = nil
    local lastName = nil
    self.lastIndex = 0
    for i = 1, 5 do
        self.gbtns[i] = self._root:findChild("Panel/Panel_bag/Panel_top/Button_"..tostring(i))
        self.gnames[i] = self._root:findChild("Panel/Panel_bag/Panel_top/name_"..tostring(i))
        self.gnames[i]:setOpacity(127)
        self.funcs[i] = function(sender)
            if lastBtn then
                lastBtn:setTouchEnabled(true)
                lastBtn:setBright(true)
            end
            if lastName then
                lastName:setOpacity(127)
            end
            self.gbtns[i]:setTouchEnabled(false)
            self.gbtns[i]:setBright(false)
            self.gnames[i]:setOpacity(255)
            lastName = self.gnames[i]
            lastBtn = self.gbtns[i]
            if self.lastIndex > 0 then
                app:sendMsg("CaptainModelRedPoint", "reqClearCollectRedPointByBagType", self.lastIndex)
            end
            self.lastIndex = i
            
            self:refreshCollectors(i)
        end
        self.gbtns[i]:addClickEventListener(self.funcs[i])
    end
    self.funcs[1]()
end

function CaptainMyCollectsView:onExit()
    -- EM:removeByName(app:getInst("CaptainController").RoomDataChange)
    self.itemNode:release()
    EM:remove(self.redpointHandler)
    app:sendMsg("CaptainModelRedPoint", "reqClearCollectRedPoint")    
end

function CaptainMyCollectsView:refreshRedPoint()
    for i = 1, 5 do
        local collects = app:sendMsg("CaptainModelRedPoint", "getFilterRedPointCollectorsByBagType", i)
        local rdp = self._root:findChild("Panel/Panel_bag/Panel_top/dot_"..tostring(i))
        if rdp then
            rdp:setVisible(#collects > 0)
        end
    end
end

function CaptainMyCollectsView:getLine(s)
    local l = cc.CSLoader:createNode(Res.TypeNode)

    l:setContentSize(l:findChild("Panel"):getContentSize())

    l:findChild("Panel/tlt"):setString(s)

    return l
end

function CaptainMyCollectsView:getRow()
    local l = ccui.Layout:create()
    l:setLayoutType(ccui.LayoutType.HORIZONTAL)
    l:setContentSize(cc.size(400,76))
    l:setBackGroundColor(cc.c3b(78, 78, 78))

    local gap = ccui.Layout:create()
    gap:setContentSize(cc.size(10, 78))
    l:addChild(gap)

    l.items = {}
    for i = 1, 5 do
        local bi = self.itemNode:clone()-- cc.CSLoader:createNode(BaseIcon)
        bi:setContentSize(bi:findChild("Panel"):getContentSize())
        l:addChild(bi)
        table.insert(l.items, bi)

        bi:findChild("Panel"):hide()
        bi:findChild("Panel/Panel_num"):hide()
        bi:findChild("Panel/level"):hide()
        bi:findChild("Panel/icon"):loadTexture("art/item_icon/itemicon_71112101.png")
        bi:findChild("Panel/selected"):hide()
        bi:findChild("Panel"):addClickEventListener(function(sender)
            bi.selectItem()
            if app:sendMsg("CaptainModelRedPoint", "getCollectorRedPoint", checknumber(bi.data.ID)) then
                app:sendMsg("CaptainModelRedPoint", "delCollectRedPoint", checknumber(bi.data.ID))
                bi:findChild("Panel/dot"):hide()
                self:refreshRedPoint()
            end
        end)

        bi.selectItem = function()
            if self.lastSelect then
                self.lastSelect:hide()
            end
            self.lastSelect = bi:findChild("Panel/selected")
            self.lastSelect:show()

            self:refreshSelectCollect(bi.data)
        end

        bi.setItem = function(data)
            bi.data = data
            bi:findChild("Panel"):show()
            if self.model then
                local mask = bi:findChild("Panel/mask")
                if self.model:hasCollect(checknumber(data.ID)) then
                    mask:hide()
                else
                    mask:show()
                end
            end
            local ygou = bi:findChild("Panel/room_e")
            local ggou = bi:findChild("Panel/room_curr")
            bi:findChild("Panel/icon"):loadTexture(data.iconPath.."/"..data.icon..".png")
            bi:findChild("Panel/grade"):loadTexture(GRes.Qulity_Icon_Bg[checknumber(data.quality)])
            if app:sendMsg("CaptainModelRedPoint", "getCollectorRedPoint", checknumber(data.ID)) then
                bi:findChild("Panel/dot"):show()
            end
        end
    end

    return l
end

function CaptainMyCollectsView:addTypeItems(items)
    local rows = {}
    local haveCount = 0
    local function getIcon(idx)
        local r = math.ceil(idx/5)
        if not rows[r] then
            rows[r] = self:getRow()
        end

        return rows[r].items[math.fmod(idx-1, 5) + 1]
    end

    for i, v in ipairs(items) do
        local icn = getIcon(i)
        icn.setItem(v)
        if i == 1 and self.lastSelect == nil then
            icn.selectItem()
        end
        if self.model:hasCollect(checknumber(v.ID)) then
            haveCount = haveCount + 1
        end
    end

    for i, v in ipairs(rows) do
        self.collectList:pushBackCustomItem(v)
    end
    return haveCount
end

function CaptainMyCollectsView:refreshCollectors(bagType)
    local types = app:sendMsg("CaptainController", "getCollectionsByBagType", bagType)
    if types == nil or #types < 1 then return end

    self.collectList:removeAllChildren()
    self.lastSelect = nil
    local haveCount = 0
    local totalCount = 0
    for k, v in ipairs(types) do
        -- if checknumber(v.type) ~= 52 then --暂时不显示底板
        local locs = app:sendMsg("CaptainController", "getLocationsByType", tostring(v.type))
        local typestr = tostring(v.type)
        if #locs > 0 then
            typestr = L(locs[1].locationName)
        else
            if checknumber(v.type) == 51 then
                typestr = L"captain_collections_typename_51"
            elseif checknumber(v.type) == 52 then
                typestr = L"captain_collections_typename_52"
            elseif checknumber(v.type) == 53 then
                typestr = L"captain_collections_typename_53"
            end
        end
        
        self.collectList:pushBackCustomItem(self:getLine(typestr))
        haveCount = haveCount + self:addTypeItems(v)
        totalCount = totalCount + #v
        -- end
    end

    self._root:findChild("Panel/Panel_bag/text"):setString(
        string.format(L("captain_mycollect_summury"), tostring(haveCount).."/"..tostring(totalCount))
        ..tostring(haveCount).."/"..tostring(totalCount)
    )
end

function CaptainMyCollectsView:initTipsIcon()
    self.typeicons = {}
    self.typeicons[11] = self._root:findChild("Panel/Panel_tips/objects_4_1")
    self.typeicons[112] = self._root:findChild("Panel/Panel_tips/objects_4_2")
    self.typeicons[14] = self._root:findChild("Panel/Panel_tips/objects_1")
    self.typeicons[13] = self._root:findChild("Panel/Panel_tips/objects_2")
    self.typeicons[12] = self._root:findChild("Panel/Panel_tips/objects_3")

    self.typeicons.default = self._root:findChild("Panel/Panel_tips/other")

    if not self.typeiconsSize then
        self.typeiconsSize = {}
        for k, v in pairs(self.typeicons) do
            self.typeiconsSize[k] = v:getContentSize()
        end
    end

    self.obtainBtn = self._root:findChild("Panel/Panel_tips/btn_obtain")
end

function CaptainMyCollectsView:hideTipsIcon()
    if self.typeicons then
        for k, v in pairs(self.typeicons) do
            v:hide()
        end
    end
end

local function centerNodes(p, nodes, gap)
    if p == nil then return end

    local panelWidth = p:getContentSize().width
    local totalWidth = 0
    if nodes and #nodes > 0 then
        for i, v in ipairs(nodes) do
            totalWidth = totalWidth + v:getContentSize().width + gap
        end

        local offx = (panelWidth - totalWidth + gap) * 0.5 + 5

        for i, v in ipairs(nodes) do
            v:setPositionX(offx + v:getAnchorPoint().x * v:getContentSize().width)
            offx = offx + v:getContentSize().width + gap
        end
    end
end

function CaptainMyCollectsView:refreshSelectCollect(data)
    self.tipsNameLbl = self._root:findChild("Panel/Panel_tips/tlt")
    self.tipsLockLbl = self._root:findChild("Panel/Panel_tips/tips")
    self.tipsDescLbl = self._root:findChild("Panel/Panel_tips/text_1")

    self:initTipsIcon()
    self:hideTipsIcon()

    if data then
        self.tipsNameLbl:setString(L(data.name))
        self.tipsNameLbl:setTextColor(Enums.QualityColor[ checknumber(data.quality) ])
        -- self.tipsLockLbl:setString(L(data.name))
        self.tipsDescLbl:setString(L(data.describe))
        local nodes = {}
        local icn = self.typeicons[checknumber(data.type)]
        local icnsize = self.typeiconsSize[checknumber(data.type)]
        if not icn then
            icn = self.typeicons.default
            icnsize = self.typeiconsSize.default
        end
        icn:show()
        -- icn:loadTexture("art/item_icon/itemicon_71112101.png")
        if self.lastMaid then
            self.lastMaid:removeFromParent()
            self.lastMaid = nil
        end

        icn:getVirtualRenderer():show()
        if checknumber(data.type) == 31 then 
            icn:getVirtualRenderer():hide()
            self:performWithDelay(function()
                local maid = AvatarFactory.createNpcById(checknumber(data.npcId))
                maid:setTag(0)
                maid:playAni({name="mapidle",next="mapidle"})
                icn:addChild(maid)
                if icnsize.height < maid:getBoundingBox().height then
                    maid:setScale(icnsize.height/maid:getBoundingBox().height)
                end
                maid:setScaleX(-maid:getScaleX())
                maid:setPosition(cc.p(icn:getContentSize().width*0.5, (icn:getContentSize().height - icnsize.height)*0.5))
                if self.lastMaid then
                    self.lastMaid:removeFromParent()
                end
                self.lastMaid = maid
            end, 0.1)
        else
            if data.showFloder and data.showArmature and string.len(data.showFloder) > 0 and string.len(data.showArmature) > 0 then
                icn:loadTexture(data.showFloder.."/"..data.showArmature..".png")
            else
                icn:loadTexture(data.floder.."/"..data.armature..".png")
            end
            local rd = icn:getVirtualRenderer()
            local osz = rd:getOriginalSize()
            local tsz = icnsize
            local owh = osz.width/osz.height
            local twh = tsz.width/tsz.height
            local fsz = nil
            if owh > twh then
                fsz = cc.size(tsz.width, tsz.width/osz.width * osz.height)
            else
                fsz = cc.size(osz.width * tsz.height/osz.height, tsz.height)
            end

            if checknumber(data.type) == 51 then
                fsz = osz
            elseif checknumber(data.type) == 11 then
                fsz = osz
            end

            icn:setContentSize(fsz)
        end

        if self.model and self.model:hasCollect(checknumber(data.ID)) then
            self.tipsLockLbl:setString(L"captain_mycollect_unlock")
            self.obtainBtn:hide()

            nodes = {self.tipsDescLbl}
        else
            self.tipsLockLbl:setString(L"captain_mycollect_lock")
            self.obtainBtn:show()
            self.obtainBtn:addClickEventListener(function(sender)
                app:sendMsg("CaptainController", "showObtainView", data.getResource, data.resourceFrom, data.name)
            end)
            nodes = {self.obtainBtn, self.tipsDescLbl}
        end
        centerNodes(self._root:findChild("Panel/Panel_tips"), nodes, 15)
    end
end

function CaptainMyCollectsView:refresh(m)
    self.model = m
    -- self:refreshCollectors(m:getOwnedCollectors())
end


return CaptainMyCollectsView